package vn.csp.gameportal;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.csp.congcu.json.JSONParser;
import vn.csp.gameportal.R;
import vn.csp.util.ThongSo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;

public class FragmentDown extends SherlockListFragment {
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		layDuLieu();// nếu muốn mỗi lần load lại tab cập nhập lại list view thì gọi anh này
		super.onCreate(savedInstanceState);
	}
    @Override
	  public void onListItemClick(ListView l, View v, int position, long id) {
	  	  Intent i = new Intent(getActivity().getApplicationContext(), GameDownload.class);
	  	  Bundle bundle = new Bundle();
	  	  bundle.putSerializable("ThongTinGameHayNhat", (Serializable) danhSachGameHayNhat.get(position));
		  i.putExtras(bundle);
		  startActivity(i);
	  }
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Kiểm tra chức năng refresh lại danh sách khi click vào nút f5
//			    Toast.makeText(getActivity().getApplicationContext(), "name", 1000).show();
//				SharedPreferences preferences = this.getActivity().getSharedPreferences("f5",0);
//				String name = preferences.getString("f5",null);
//				if(name != null){
//					//Toast.makeText(getActivity().getApplicationContext(), name, 1000).show();
//					if(name.equals("1")){
//						Toast.makeText(getActivity().getApplicationContext(), "layDuLieu();", 1000).show();
////						layDuLieu();
//					}
//					SharedPreferences preferences1 = this.getActivity().getSharedPreferences("f5", 0);
//			    	Editor editor = preferences1.edit();
//			    	editor.clear();
//			    	editor.commit();
//				}
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	/** Danh sách game mới nhất ./. */
	List<ThongTinGame> danhSachGameHayNhat = new ArrayList<ThongTinGame>();
	public void layDuLieu() {
		new Thread(){
			@Override
			public void run() {
				JSONParser jsonParser = new JSONParser();
		        try {
		        	ThongSo thongSo = new ThongSo();
		        	JSONObject jsonObject = jsonParser.getJSONFromUrl(thongSo.URL,thongSo.CODE_PHP,ThongSo.YEU_CAU.GAME_TAI_NHIEU.toString());
		        	JSONArray androidArray = jsonObject.getJSONArray("JSONResponse");
		        	for (int i = 0; i < androidArray.length(); i++) {
		        		danhSachGameHayNhat.add(new ThongTinGame(androidArray.getJSONObject(i).getString("TTG_ID"), 
	    				androidArray.getJSONObject(i).getString("TTG_TEN_GAME"), 
	    				androidArray.getJSONObject(i).getString("TTG_ICON"), 
	    				androidArray.getJSONObject(i).getString("TTG_LUOT_XEM"), 
	    				androidArray.getJSONObject(i).getString("TTG_LUOT_TAI"), 
	    				androidArray.getJSONObject(i).getString("TTG_DUONG_DAN"), 
	    				androidArray.getJSONObject(i).getString("TLG_TEN_THE_LOAI"),
	    				androidArray.getJSONObject(i).getString("DG_SODIEM"),
	    				androidArray.getJSONObject(i).getString("TTG_NOI_DUNG_MO_TA")
    				));
					}
		        	Message m = myHandler.obtainMessage();
					myHandler.sendMessage(m);
				} catch (Exception e) {
					Message m = myHandler.obtainMessage();
					Bundle b = new Bundle();
					b.putString("thong_diep_loi", "Vui lòng kiểm tra kết nối.");
					m.setData(b);
					myHandler.sendMessage(m);
				}
			}
		}.start();
	}
	Handler myHandler = new Handler() {
		public void handleMessage (Message m) {
			String thong_diep_loi = m.getData().getString("thong_diep_loi");
			if(thong_diep_loi!=null){
				Toast.makeText(getActivity().getApplicationContext(),thong_diep_loi, Toast.LENGTH_SHORT).show();
			}else{
				if (!danhSachGameHayNhat.isEmpty()){
					List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
					//http://wptrafficanalyzer.in/blog/android-listfragment-with-images-and-text-using-android-support-library/
					int count = 0;
					Enumeration<ThongTinGame>  e = Collections.enumeration(danhSachGameHayNhat);
					while(e.hasMoreElements()){
						ThongTinGame gameMoiNhat = e.nextElement();
						String x = gameMoiNhat.getTTG_DUONG_DAN();
			            HashMap<String, String> hm = new HashMap<String,String>();
			            hm.put("icon", Integer.toString(R.drawable.icons) ); //?????? thay thế bằng hình thiệt trong db
			            hm.put("ten_game", ++count+ ". " + gameMoiNhat.getTTG_TEN_GAME());
			            hm.put("the_loai","Thể loại : " + gameMoiNhat.getTLG_TEN_THE_LOAI());
			            hm.put("luot_xem","Lượt xem: " + gameMoiNhat.getTTG_LUOT_XEM() + " Lượt tải: "+ gameMoiNhat.getTTG_LUOT_TAI());
			            aList.add(hm);
					  }
			        // Keys used in Hashmap
			        String[] from = {"icon", "ten_game","the_loai","luot_xem" };
			        // Ids of views in listview_layout
			        int[] to = { R.id.icon,R.id.tengame,R.id.chude,R.id.luotxem};
			        // Instantiating an adapter to store each items
			        // R.layout.listview_layout defines the layout of each item
			        SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to);
			 
			        setListAdapter(adapter);
				}
			}
		}
	};
	 public void thongBao(String noiDung){
	    	Toast.makeText(getActivity().getApplicationContext(), noiDung, Toast.LENGTH_LONG).show();
	    }
}
